package com.niodata.dp.task.dao.handler;

import com.niodata.dp.mybatis.DpMybatisTypeHandler;
import com.niodata.dp.task.entity.TaskParams;
import com.niodata.dp.util.JsonUtil;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class TaskParamsTypeHandler extends BaseTypeHandler<TaskParams>
    implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGVARCHAR;
  }

  @Override
  public Class<TaskParamsTypeHandler> getTypeHandlerClass() {
    return TaskParamsTypeHandler.class;
  }

  @Override
  public Class<TaskParams> getJavaClass() {
    return TaskParams.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, TaskParams parameter,
      JdbcType jdbcType) throws SQLException {
    try {
      ps.setString(i, JsonUtil.toJson(parameter));
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }

  }

  @Override
  public TaskParams getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String json = rs.getString(columnName);
    if (json == null || json.length() == 0) {
      return null;
    }
    try {
      return JsonUtil.fromJson(TaskParams.class, json);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public TaskParams getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String json = rs.getString(columnIndex);
    if (json == null || json.length() == 0) {
      return null;
    }
    try {
      return JsonUtil.fromJson(TaskParams.class, json);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public TaskParams getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String json = cs.getString(columnIndex);
    if (json == null || json.length() == 0) {
      return null;
    }
    try {
      return JsonUtil.fromJson(TaskParams.class, json);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
